package com.customers.listener;

import com.customers.util.ConnectJDBC;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

@WebListener("/*")
public class JDBCListener implements ServletContextListener {
    private static Connection connection = null;

    @Override
    public void contextInitialized(ServletContextEvent sce) {

        ResourceBundle resourceBundle = ResourceBundle.getBundle("JDBC");
        String driver = resourceBundle.getString("driver");
        String url = resourceBundle.getString("url");
        String root = resourceBundle.getString("root");
        String password = resourceBundle.getString("password");
        InputStream is = null;

        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, root, password);
            connection.setAutoCommit(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        sce.getServletContext().setAttribute("jdbc", connection);
        ConnectJDBC.setConnection(sce);

        //读取xml，只创建一次Service和Dao
        try {
            is = this.getClass().getClassLoader().getResourceAsStream("MySql1.xml");
            SAXReader reader = new SAXReader();
            Document document = reader.read(is);
            Element sqlelement = document.getRootElement();     //root
//            XmlReadUtil.setElement(sqlelement);
            Object service = null;
            Object dao = null;

            List<Element> elements = sqlelement.elements();   //service

            //创建service实体
            for (Element serviceelement : elements) {                //service
                String serviceName = serviceelement.attributeValue("Service");
                String serviceId = serviceelement.attributeValue("ServiceId");
                Class<?> serviceClass = Class.forName(serviceName);
                service = serviceClass.newInstance();

                //创建dao实体
                List<Element> daoelements = serviceelement.elements();   //dao
                for (Element daoelement : daoelements) {                 //dao
                    Map<String, String> sqlMap = new HashMap<>();
                    String daoName = daoelement.attributeValue("Dao");
                    String daoId = daoelement.attributeValue("DaoId");
                    String daoInteface = daoelement.attributeValue("DaoInterface");
                    List<Element> sqlelements = daoelement.elements();
                    for (Element element1 : sqlelements) {                  //sql语句
                        String id = element1.attributeValue("id");
                        String sql = element1.getTextTrim();
                        sqlMap.put(id, sql);
                    }
                    Class<?> daoClass = Class.forName(daoName);
                    dao = daoClass.newInstance();
                    Method setMapMethod = daoClass.getDeclaredMethod("setSqlMap",Map.class);
                    setMapMethod.invoke(dao,sqlMap);

                    Method setDaoMethod = serviceClass.getDeclaredMethod("set"+daoId,Class.forName(daoInteface));
                    setDaoMethod.invoke(service,dao);
                }
                System.out.println("serviceId:"+serviceId);
                System.out.println("service:"+service);
                sce.getServletContext().setAttribute(serviceId, service);
            }





//            ConnectJDBC.setSqlelement(sqlelement);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
